# -*- coding: utf-8 -*-
import MythTV, BeautifulSoup, urllib2, time, os, sys

class Dtv_multiplex( MythTV.DBDataWrite ):
    def __str__(self):
        if self._wheredat is None:
            return u"<Uninitialized Dtv at %s>" % hex(id(self))
        return u"<Dtv_multiplex '%d' at %s>" % \
            (self.mplexid, hex(id(self)))

    def __repr__(self):
        return str(self).encode('utf-8')

sskos = { }

chlineupx = [
    ["TVE International",  1],
    ["Canal 24 Horas"],
    ["TF 1", 11, 6 ],
    ["M6 HD"],
    ["M6"],
    ["W9"],
    ["France 2", 15, 1],
    ["France 3 Sat"],
    ["France 5"],
    ["France Ô"],
    ["TMC (Télé Monte Carlo)"],
    ["LCP - La Chaîne Parlementaire"],
    ["Demain !"],
    ["KTO"],
    ["TV8 Mont Blanc"],
    ["NRJ Paris Sat"],
    ["Mirabelle TV"],
    ["Normandie TV"],
    ["TéléGrenoble Isère"],
    ["TLP - Télé Locale Provence"],
    ["Vosges Television"],
    ["Canal+ Promo", 31, 5],
    ["Arte HD"],
    ["Arte (Germany)"],
    ["Arte (France)"],
    ["Direct 8"],
    ["""TELE" HREF="http://www.itele.fr/" TARGET="_blank">i-Télé"""], # i-Télé
    ["BFM Business"],
    ["BFM TV"],
    ["Montagne TV"],
    ["BBC One London", 101, 3],
    ["BBC Two England"],
    ["ITV 1 London"],
    ["Channel 4 London"],
    ["Channel 5 London"],
    ["BBC Three"],
    ["BBC Four"],
    ["BBC One HD"],
    ["BBC HD"],
    ["BBC Alba"],
    ["ITV 1 London +1", 112],
    ["ITV 2"],
    ["ITV 2 +1"],
    ["ITV 3"],
    ["ITV 3 +1"],
    ["ITV 4"],
    ["ITV 4 +1"],
    ["ITV HD"],
    ["S4C Digidol"],
    ["Channel 4 London +1"],
    ["E4 UK"],
    ["E4 +1"],
    ["More 4"],
    ["More 4 +1"],
    ["Channel 4 HD"],
    ["Channel 5 +1"],
    ["5 USA"],
    ["5 USA +1"],
    ["5*"],
    ["5* +1"],
    ["CBS Drama", 134],
    ["CBS Reality"],
    ["CBS Reality +1"],
    ["CBS Action"],
    ["Horror Channel"],
    ["Horror Channel +1"],
    ["BET U.K."],
    ["BET +1"],
    ["True Entertainment"],
    ["Men & Movies"],
    ["BBC News", 200],
    ["BBC Parliament", 201],
    ["Al Jazeera English", 203],
    ["EuroNews"],
    ["France 24 (in English)"],
    ["Russia Today"],
    ["CNN International Europe"],
    ["Bloomberg U.K."],
    ["NHK World HD"],
    ["CNBC Europe"],
    ["Film4", 300],
    ["Film4 +1"],
    ["True Movies 1"],
    ["True Movies 2"],
    ["Movies4men"],
    ["Movies4Men +1"],
    ["Movies4Men 2"],
    ["Movies4Men 2 +1"],
    ["Wedding TV", 400],
    ["Information TV", 402],
    ["Showcase"],
    ["Food Network", 405],
    ["Food Network +1"],
    ["Chart Show TV", 500],
    ["The Vault"],
    ["Flava"],
    ["Scuzz"],
    ["B4U Music"],
    ["Zing", 509],
    ["Clubland TV", 514],
    ["Vintage TV"],
    ["NME TV"],
    ["Bliss"],
    ["Massive R&B"],
    ["CBBC", 600],
    ["CBeebies"],
    ["CITV U.K."],
    ["Pop"],
    ["PopGirl"],
    ["Tiny Pop"],
    ["Kix"],
    ["Ocean Finance TV", 650],
    ["Renault TV"],
    ["Psychic TV"],
    ["INI - Inspiration Network International", 690],
    ["Daystar TV Network"],
    ["Revelaton TV"],
    ["Islam Channel"],
    ["GOD Europe"],
    ["SonLife Broadcasting Network"],
    ["QVC U.K.", 800],
    ["Price Drop TV"],
    ["Bid TV"],
    ["Pitch TV"],
    ["Pitch TV World"],
    ["Gems.tv"],
    ["TV Shop U.K."],
    ["Jewellery Maker"],
    ["JML Home & DIY"],
    ["JML Cookshop"],
    ["Ideal Extra"],
    ["Ideal World", 812],
    ["Create & Craft"],
    ["Speed Auction TV"],
    ["Jewellery Channel"],
    ["QVC Beauty"],
    ["Rocks & Co"],
    ["Gems TV Extra"],
    ["Babestation", 870],
    ["Filth", 874],
    ["Magyar TV 2", 901, 6],
    ["Duna 1 HD"],
    ["Duna World HD"]
    ]


chlineup = { }

def channels( ):
    print "verifying and deleting channels"
    ss = { } # verified channels
    dd = { } # mplexes
    kcns = { } # KOS channels by name
    cs = MythTV.Channel.getAllEntries()
    dtv = Dtv_multiplex.getAllEntries()
    delcount = 0
    for d in dtv:
        dd[d.mplexid] = d
    for c in cs:
        """
        if c.name == '' or c.name == '.' or c.name.isdigit():
            print "delete " + c.channum + " '" + c.name + "'"
            c.delete()
            continue
        """
        ssk = sskos.get(c.sourceid, None)
        if ssk != None:
            srv_found = None
            pol_found = ssk.get(dd[c.mplexid].polarity, None)
            if pol_found != None:
                freq_search = int(round(float(dd[c.mplexid].frequency) / 1000.0))
                freq_found = pol_found.get(freq_search, None)
                if freq_found == None:
                    freq_search += 1
                    freq_found = pol_found.get(freq_search, None)
                if freq_found == None:
                    freq_search -= 2
                    freq_found = pol_found.get(freq_search, None)
                if freq_found != None:
                    srv_found = freq_found.get(c.serviceid, None)
            if srv_found == None:
                print "delete " + c.channum + ", " + c.name + ", " + str(dd[c.mplexid].frequency) + ",  " + str(int(round(float(dd[c.mplexid].frequency) / 1000.0))) + ", " + str(c.serviceid)
                delcount += 1
                c.delete()
                continue
            else:
                if srv_found != "_":
                    kcn = kcns.get(srv_found, None)
                    if kcn == None:
                        kcn = [ ]
                        kcns[srv_found] = kcn
                    kcn.append(c)
        if c.sourceid in ss:
            l = ss[c.sourceid]
        else:
            l = []
            ss[c.sourceid] = l
        l.append(c)

    print "deleted: " + str(delcount)

    print "finding requested channels"
    cc = 0
    prefsrc = 0
    for lu in chlineupx:
        if len(lu) < 2 or lu[1] == 0:
            cc += 1
        else:
            cc = lu[1]
        if len(lu) > 2:
            prefsrc = lu[2]
        cf = kcns.get(lu[0], None)
        print str(cc) + " : " + lu[0] + " :",
        if cf == None:
            print("NOT FOUND")
            print("# DISABLED - CHANNEL NOT FOUND")
        else:
            if len(cf) == 1:
                print("OK : " + cf[0].name + " (" + str(cf[0].sourceid) + ", " + str(cf[0].chanid) + ")")
                if prefsrc != 0 and cf[0].sourceid != prefsrc:
                    print("# DISABLED - NOT PREFERRED SAT")
                else:
                    chlineup[cf[0].chanid] = str(cc)
            else:
                print "MULTIPLE " + str(len(cf))
                onlyone = 0
                for mcf in cf:
                    if prefsrc == 0:
                        print("- " + mcf.name + " (" + str(mcf.sourceid) + ", " + str(mcf.chanid) + ")")
                    else:
                        print "- " + mcf.name + " (" + str(mcf.sourceid) + ", " + str(mcf.chanid) + ")",
                        if mcf.sourceid == prefsrc:
                            if onlyone == 0:
                                onlyone = mcf.chanid
                                print ": SAT FOUND"
                            else:
                                onlyone = -1
                                print ": SAT DUPLICATE"
                        else:
                            print ": -"
                if onlyone > 0:
                    chlineup[onlyone] = str(cc)
                else:
                    print("# DISABLED - AMBIGUOUS")

    print "renumbering"
    for si in ss.keys():
        ss[si].sort(key = lambda channel: channel.name.lower())
        nn = 1
        for c in ss[si]:
#            print str(si) + ", " + c.name + ", " + c.channum + ", " + str(si) + "%03d"%nn
            rchid = chlineup.get(c.chanid, None)
            if (rchid == None):
                c.update(channum = str(si) + "%03d"%nn)
                nn += 1
            else:
                print rchid + ", " + c.name
                c.update(channum = rchid)

def kingofsat( ):            
    urls = { 1: "http://en.kingofsat.net/pos-5W-fta.php",
             2: "http://en.kingofsat.net/pos-7E-fta.php",
             3: "http://en.kingofsat.net/pos-28.2E-fta.php",
             5: "http://en.kingofsat.net/pos-19.2E-fta.php",
             6: "http://en.kingofsat.net/pos-9E-fta.php",
             7: "http://en.kingofsat.net/pos-30W-fta.php",
             8: "http://en.kingofsat.net/pos-13E-fta.php",
             9: "http://en.kingofsat.net/pos-0.8W-fta.php" }
    #urls = [ "file:///home/Koma/test.html" ]

    current_time = time.time()
    for sat in urls.keys():
        sskos[sat] = { }
        cacheFileName = "cache" + str(sat) + ".html"
        if os.path.isfile(cacheFileName) and current_time - os.path.getmtime(cacheFileName) < 86400:
            print(cacheFileName)
            cacheFile = open(cacheFileName, "r")
            html = cacheFile.read()
            cacheFile.close()
        else:
            print(urls[sat])
            html = urllib2.urlopen(urls[sat]).read()
            cacheFile = open(cacheFileName, "w")
            cacheFile.write(html)
            cacheFile.close()
        soup = BeautifulSoup.BeautifulSoup(html, convertEntities = BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
        tbls = soup.findAll("table")
        frq = None
        pol = None
        for tbl in tbls:
            cl = tbl.get("class", "")
            if cl == "frq":
                pol = tbl.find("td", { "class": ["bld", "nbld"], "width": "2%" }).contents[0].lower()
                if pol == None:
                    raise Exception
                if sskos[sat].get(pol, None) == None:
                    sskos[sat][pol] = { }
                frq = int(round(float(tbl.find("td", { "class": ["bld", "nbld"], "width": "5%" }).contents[0])))
                if sskos[sat][pol].get(frq, None) == None:
                    sskos[sat][pol][frq] = { }
            if cl == "fl":
                if frq == None or pol == None:
                    raise Exception
                fls = tbl.findAll("tr")
                for fl in fls:
                    service = fl.find("td", { "class": "s", "width": "5%" })
                    if service != None:
                        service = service.contents[0]
                    channel_name = fl.find("a", { "class": "A3" })
                    if channel_name != None:
                        channel_name = str(channel_name.contents[0])
                    if channel_name == None:
                        channel_name = "_"
                    if service != None and service.isdigit():
                        print str(frq) + str(pol) + ", " + str(int(service)) + ", " + channel_name
                        sskos[sat][pol][frq][int(service)] = channel_name

kingofsat()
channels()
